﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using __ts.Core.Utilities;

namespace CCU.PackageBuilder
{
    static class Program
    {
        // Mutex
        static Mutex mutex = new Mutex(true, "{7f9ea222-40fb-46bc-ab80-d825763240a0}");

        /// <summary>
        /// Program entry point.
        /// </summary>
        [STAThreadAttribute]
        private static void Main(string[] args)
        {
            if (!Util.IsRuningWithAdministrator())
            {
                MessageBox.Show("Must run with administrator.", "Error");
                return;
            }

            // No instances
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {

                // Create main form
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new MainForm());

                // Release Mutex
                mutex.ReleaseMutex();

                // Disallow multiple istances
            }
            else
            {

                // Open previous instance
                NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);

            }

        }
        internal class NativeMethods
        {
            public const int HWND_BROADCAST = 0xffff;
            public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
            [DllImport("user32")]
            public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
            [DllImport("user32")]
            public static extern int RegisterWindowMessage(string message);
            [DllImportAttribute("user32.dll")]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }
    }
}
